相关疑难解决方法(0)

等待多个并发等待操作

如何更改以下代码,以便触发异步操作并同时运行?

const value1 = await getValue1Async();
const value2 = await getValue2Async();
// use both values
Run Code Online (Sandbox Code Playgroud)

我需要做这样的事情吗?

const p1 = getValue1Async();
const p2 = getValue2Async();
const value1 = await p1;
const value2 = await p2;
// use both values
Run Code Online (Sandbox Code Playgroud)

javascript promise async-await es2017

31
推荐指数
2
解决办法
3820
查看次数

将已解决的承诺值传递到最终"然后"链的最佳方法是什么

我正在尝试使用node.js中的Q模块来了解promises,但是我有一个小问题.

在这个例子中:

ModelA.create(/* params */)
.then(function(modelA){
    return ModelB.create(/* params */);
})
.then(function(modelB){
    return ModelC.create(/* params */);
})
.then(function(modelC){

    // need to do stuff with modelA, modelB and modelC

})
.fail(/*do failure stuff*/);
Run Code Online (Sandbox Code Playgroud)

.create方法在每个.then()中返回一个promise,正如预期的那样,获取promise的已解析值.

但是在最后的.then()中,我需要拥有所有3个先前解析的promise值.

最好的方法是什么?

javascript node.js promise

26
推荐指数
2
解决办法
2万
查看次数

删除嵌套的promise

我是承诺并使用NodeJS中的请求和承诺编写网络代码的新手.

我想删除这些嵌套的promises并将它们链接起来,但我不确定我是怎么做的/它是否是正确的方法.

exports.viewFile = function(req, res) {
var fileId = req.params.id;
boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
    .then(function(response) {
        boxViewerRequest('documents', {url: response.request.href}, 'POST')
            .then(function(response) {
                boxViewerRequest('sessions', {document_id: response.body.id}, 'POST')
                    .then(function(response) {
                        console.log(response);
                    });
            });
    });
};
Run Code Online (Sandbox Code Playgroud)

这是请求代码:

var baseContentURL = 'https://api.box.com/2.0/';
var baseViewerURL = 'https://view-api.box.com/1/';

function boxContentRequest(url, accessToken) {
    return new Promise(function (resolve, reject) {
            var options = {
                url: baseContentURL + url,
                headers: {
                    Authorization: 'Bearer ' + accessToken,
                }
            };
      request(options, function (err, res) {
        if (err) { …
Run Code Online (Sandbox Code Playgroud)

javascript request node.js promise

19
推荐指数
1
解决办法
4454
查看次数

如何在Parse Promise链中传递额外数据

在我的Parse Cloude代码中,我需要运行几个连续的查询,每个查询都使用"find()".

例:

var promise = firstQuery.get(objectId).then(function(result1){
            return secondQuery.find();
        }).then(function(result2){
            return thirdQuery.find();
        }).then(function(result3) {

             // here I want to use "result1", "result2" and "result3"
        });
Run Code Online (Sandbox Code Playgroud)

问题是:如何在最后的"then"语句中访问"result1"和"result2",而不将它们分配给父作用域中声明的变量.

为什么我这样问:如果要嵌套一堆你在循环中创建的promises以便它们并行执行,你就不能使用父作用域技巧(想象一下围绕上述语句的for循环,其中所有的promise都是放入一个数组然后使用"Parse.Promise.when"进行评估.它们都会同时开始修改父作用域变量.)

我可以创建某种承诺对象,我可以返回以下内容:

Parse.promise({result:result1,findResult:secondQuery.find()};
Run Code Online (Sandbox Code Playgroud)

所以我可以通过这样做从"result2"参数中获取值

result2.result 
Run Code Online (Sandbox Code Playgroud)

result2.findResult
Run Code Online (Sandbox Code Playgroud)

我希望我能说清楚.这不是很容易解释.

javascript promise parse-platform parse-cloud-code

14
推荐指数
2
解决办法
1万
查看次数

Sequelize中的承诺:如何从每个承诺中获得结果

在Sequelize> = 1.7中,我们可以使用promises

你能解释一下我如何从这个代码中获得每个用户的值:

var User = sequelize.define("user", {
  username: Sequelize.STRING
})


User
  .sync({ force: true })
  .then(function() { return User.create({ username: 'John' }) })
  .then(function(john) { return User.create({ username: 'Jane' }) })
  .then(function(jane) { return User.create({ username: 'Pete' }) })
  .then(function(pete) {
    console.log("we just created 3 users :)")
    console.log("this is pete:")
    console.log(pete.values)

    // what i want:
    console.log("this is jane:")
    console.log(jane.values)

    console.log("this is john:")
    console.log(john.values)
  })
Run Code Online (Sandbox Code Playgroud)

UPD

所有值都需要与其他模型设置关联.其实我需要一些像这样的代码:

User.hasMany(Group)
Group.hasMany(User)

User
  .sync({ force: true })
  .then(function() { return User.create({ …
Run Code Online (Sandbox Code Playgroud)

javascript promise sequelize.js bluebird

12
推荐指数
2
解决办法
2万
查看次数

处理嵌套Promise的最佳方法(bluebird)

我在下面有以下承诺链,它看起来很混乱(每个_create*函数返回一个承诺):

return new Promise(function (resolve, reject) {
      _this.database.transaction(function (t) {
        _this._createExternalAccount(payment, t)
          .then(function (externalAccount) {
            return _this._createExternalTransaction(externalAccount, payment, t)
              .then(function (externalTransaction) {
                return _this._createAddress(externalAccount, payment, t)
                  .then(function (address) {
                    return _this._createTransaction(address, payment, t)
                      .then(function (transaction) {
                        return _this._createGatewayTransaction(externalTransaction, transaction, payment, t)
                          .then(function (gatewayTransaction) {
                            t.commit();
                            resolve(bridgePayment);
                          });
                      });
                  });
              });
          })
          .error(function (bridgePayment) {
            t.rollback();
            reject(bridgePayment);
          });
      });
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用Promise函数all(),join()但这些似乎同时运行我无法执行的函数,因为持久化到某些表需要来自先前持久化表的字段.我希望有一些方法让我做以下的事情,但我似乎无法找出如何:

Promise.all(_this._createExternalAccount(payment, t), _this._createExternalTransaction(externalAccount, payment, t), _this._createAddress(externalAccount, payment, t))
    .then(function(externalAccount, externalTransaction, address) {
        // do logic …
Run Code Online (Sandbox Code Playgroud)

javascript promise bluebird

12
推荐指数
1
解决办法
7374
查看次数

如何打破承诺链

我是这样的承诺,

function getMode(){
    var deferred = Promise.defer();

    checkIf('A')
    .then(function(bool){
        if(bool){
            deferred.resolve('A');
        }else{
            return checkIf('B');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('B');
        }else{
            return checkIf('C');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('C');
        }else{
            deferred.reject();
        }
    });

    return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

checkIf返回一个promise,是的checkIf ,无法修改.

我如何在第一场比赛中脱颖而出?(除了明确抛出错误之外的任何其他方式?)

javascript promise selenium-chromedriver selenium-webdriver

12
推荐指数
3
解决办法
2万
查看次数

如何使用诺言避免回调地狱?

所以我有一个帖子集合

{
  id: String,
  comments: [String], # id of Comments
  links: [String], #id of Links
}
Run Code Online (Sandbox Code Playgroud)

评论:{id:String,comment:String,}

链接:{id:String,link:String,}

通过ID查找包含评论和链接的帖子:

Posts.findOne({id: id}, function(post) {
  Comments.find({id: post.id}, function(comments) {
    Links.find({id: post.id}, function(links) {
      res.json({post: post, comments: comment, links: links})
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

如何使用Promise(http://mongoosejs.com/docs/promises.html)来避免回调地狱?

var query = Posts.findOne({id: id});
var promise = query.exec();

promise.then(function (post) {
  var query1 = Comments.find({id: post.id});
  var promise1 = query1.exec();
  promise1.then(function(comments) {
    var query2 = Links.find({id: post.id});
    var promise2 = query2.exec();
    promise2.then(function(links) {
      res.json({post: post, comments: …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose node.js promise

11
推荐指数
1
解决办法
7486
查看次数

承诺关闭?

闭包标签维基页面中,它显示"jQuery本身就是一个大关闭".

但是也承诺关闭?你能解释一下为什么或为什么不解释?这就是我理解闭包的方法:为变量分配一个函数并在不同的环境中重用它.Promise可以做到这一点$.ajax(),但我无法在stackoverflow中找到将promise作为闭包引入的任何地方.也许是因为有像承诺的其他功能$.Deferred(),resolve()以及fail()扩展其功能,而不仅仅是一个简单的函数传递?

javascript closures promise

10
推荐指数
3
解决办法
5440
查看次数

在Javascript中通过一系列承诺传递状态有哪些模式?

我正在尝试学习一些关于Node和异步编程的知识.我读到了Promises,并试图在一个小项目中使用它们,这个项目将用户的帖子从服务A复制到服务B.我在理解如何最好地在Promises之间传递状态时遇到一些麻烦

该项目是使用Promise库为NodeJS编写的

我当前问题的一个简单定义是:

  • 如果服务B中尚不存在帖子,则将用户的帖子从服务A复制到服务B.
  • 这两种服务都提供http API,需要一个不易记忆的用户ID来查找该用户的帖子,因此必须从用户名中查找用户ID.
  • 所有的http调用都是异步的.

这是一些伪代码,说明了我如何将Promise链接在一起.

Promise.from('service_A_username')
  .then(getServiceAUserIdForUsername)
  .then(getServiceAPostsForUserId)
  .then(function(serviceAPosts) {
    // but what? store globally for access later?
    doSomethingWith(serviceAPosts);
    return Promise.from('service_B_username');
  })
  .then(getServiceBUserIdForUsername)
  .then(getServiceBPostsForUserId)
  .done(function(serviceBPosts) {
    // how do we interact with Service A posts?
    doSomethingThatInvolvesServiceAPostsWith(serviceBPosts); 
  });
Run Code Online (Sandbox Code Playgroud)

我想过要做的一些事情:

  1. 将getIdForUsername调用带入getPostsForUserId函数.但是,我希望保持每个功能单元尽可能简单,遵循"做一件事,做得好"的原则.
  2. 创建一个"上下文"对象并将其传递给整个链,在此对象中读取和存储状态.然而,这种方法使得每个功能都非常适用于链条,因此难以单独使用.

还有其他选择,建议采用什么方法?

javascript asynchronous chaining node.js promise

9
推荐指数
2
解决办法
1353
查看次数