javascript - 有没有办法在 promise 的 .then 部分中传递自定义数据?

标签 javascript promise bluebird bookshelf.js

我对 Promise 还很陌生(我正在将 Bluebird Promise 与 ExpressJS 一起使用)。我喜欢他们整理代码的方式。但是,我不太确定在某些情况下如何使用它们。我什至不确定我在示例中是否正确使用了它们。

我遇到的问题是我想将一些真实或虚假的信息传递给 promise 的“.then”部分。我已对下面的代码进行了注释以获取更多详细信息。

提前谢谢您!

//data is an array of javascript objects
Promise.each(data, function(d){
    delete d.offset;
    if (d.driver_id == -1) d.driver_id = null;  

    Promise.try(function(){
        return new Term().where({'date_of_driving': d.date_of_driving}).fetch()
    })
    .then(function(result){

        d.updated_at = dater.formatDate(new Date(), true);
        if (result !== null) {
            //update
            var res = result.toJSON();
            return new Term({'id': res.id}).save(d);
        } else {
            //save
            d.created_at = dater.formatDate(new Date(), true);
            return new Term().save(d);               
        }
    }).then(function(item){
            //I need to know here if before I saved or updated Term record
            //is there a way to pass a truthy or falsy variable?
    })
})
.then(function(terms){

})
.catch(function(error){
    callback(false);
});

最佳答案

I'm not even sure I'm using them right in my example.

您似乎忘记了从 each() 回调中返回一个 promise 。另外,我不确定您是否需要 Promise.try 包装器,我认为直接使用 .fetch() 返回的 Promise 应该非常安全。

The issue I have is that I'd like to pass some truthy or falsy to ".then" part of the promise.

我认为这里最简单的方法是嵌套 then 调用,并将回调放在相应的 .save() 调用的右侧。

return new Term().where({'date_of_driving': d.date_of_driving}).fetch()
.then(function(result){
    d.updated_at = dater.formatDate(new Date(), true);
    if (result !== null) {
        var res = result.toJSON();
        return new Term({'id': res.id}).save(d) // update
        .then(function(item) {
            // here you know that before you updated the Term record
        });
    } else {
        d.created_at = dater.formatDate(new Date(), true);
        return new Term().save(d) // save
        .then(function(item) {
            // here you know that before you saved the Term record
        });
    }
})

基本上,如果您的问题归结为访问 result !== null 表达式,请参阅 How do I access previous promise results in a .then() chain?对于其他方法。

关于javascript - 有没有办法在 promise 的 .then 部分中传递自定义数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28926055/

相关文章:

javascript - Protractor ,需要创建键: value pair的字典

javascript - 在查看图表值方面需要帮助

javascript - 页面完全加载后运行 javascript 自动滚动功能

javascript - Loop、DNS 和 Bluebird Js - Promise 仍然异步工作

javascript - 如何正确使用带有异步函数的 Promise.all() 和 then()?

javascript - 使用 bluebird .reduce 将参数传递给一系列 Promise

javascript - Node.js - 将数据发送到 Node.js 并以 HTML 形式验证插入的数据

javascript - AngularJS : Adding variable into a chain of promises

node.js - 使用 node.js 并 promise 获取分页数据

node.js - Node : How to wait for server start at http://localhost:8000