javascript - 如何获取 Bluebird Promise.settle() 的 promise 值?

标签 javascript promise bluebird

当我使用 Promise.map() 时,我要么得到一个 user_ids 数组,要么得到一个错误。当我使用 Promise.settle() 时,我获取的是数组的值,而不是数组中返回的 Promise 的值。我使用以下内容来更好地说明我的意思:

var Promise = require('bluebird');
var user_names = ['John','Mary'];

Promise.map(user_names, function(name){
    //following will return a promise resolved with the db id
    // or a rejection
    return db.create(name);
}).then(function(user_ids){
    //if db.create never failed I get an array of db ids
    console.log(user_ids); //returns ['1','2']
}).catch(function(err){
    //at least one of the db.create() failed
});

Promise.settle(user_names, function(name){
    //following will return a promise resolved with the db id
    // or a rejection
    return db.create(name);
}).then(function(results){
    //I get an array of PromiseInspection objects
    if(results[0].isFulfilled()){
        var value = results[0].value();
        console.log(value); //returns 'John'
    }
});

我的最终目标是取回一组 id。由于 Promise 可能被拒绝,该数组可能比 user_names 数组小。

最佳答案

Promise.settle确实像 Promise.all 一样工作,而不是像 Promise.map 那样工作。它不接受一组值和回调,它接受一组promise(如果给定值,它会将它们解析为promise)。您的回调将被忽略。

您将自己调用该函数,使用 Array's .map method :

Promise.settle(user_names.map(function(name) {
//                       ^^^^^
    return db.create(name);
})).then(function(results) {
    if (results[0].isFulfilled()) {
        var value = results[0].value();
        console.log(value); // returns the database id now
    }
});

关于javascript - 如何获取 Bluebird Promise.settle() 的 promise 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236236/

相关文章:

javascript - 是否可以将生成器中的项目异步收集到数组中?

javascript - 使用 QJSEngine 在 Qt 中执行 Javascript 的速度

javascript - 使用 GoJS initialAutoscale 图属性时遇到问题 - 它是如何工作的?

javascript - 从原始 HTML 检测 ajax 请求

javascript - Bluebird promise 本质上是阻塞的吗

javascript - 如何等待 Mongoose 搜索的返回?

javascript - PHP中的数组,Json

javascript - 为什么 promise 的执行函数 arg 名为 resolve()?

backbone.js - jQuery Promise 和 Backbone

javascript - 如何处理图像背景的加载状态?