【问题标题】:How to break a loop that trigger from an inner promise function?如何打破从内部承诺函数触发的循环?
【发布时间】:2018-09-29 15:24:11
【问题描述】:

如何打破续集承诺 .then({})。我想打破 then 承诺的出口并打破循环。如果条件触发。代码与以下相同。不是我的确切代码。

int i = 0;
   while(i<result.length){

      db.Model.findAll({
      where:{
         x : X,
         w : W,
         z : z
      }).then(result => {
        if(result[i].x == null || result[i].x == undefined){
             // update and break here!
             update(): // something like that
             // how i break the outer loop.
        }
        if(result[i].w > 0){
             // how i break the outer loop.
        }
        if(result[i].z < 100){
             // how i break the outer loop.
        }
   })
 i++;
}

【问题讨论】:

  • 嗯,我不完全理解这里发生了什么,但是为什么一个简单的break 表达式不起作用?也许像 result.some() 这样的东西,然后在你想休息时返回 true 可能会更好。
  • 寻找取消令牌或者你可以使用bluebird
  • 我很抱歉,我有一个错误的示例代码给你。 e 更新了示例,希望您现在可以得到它。谢谢。
  • 我不明白您的编辑。 result 未定义。
  • 2 个问题.. 1) 一遍又一遍地执行相同的数据库查询有什么意义..? 2) 你必须将你的while 循环移动到then 阶段,并为下一个then 阶段返回一些有意义的东西。

标签: javascript node.js promise sequelize.js


【解决方案1】:

您只需要async / await 并像这样实现它:

async function your_function(){
    // init your result varibale
    for(let i=0 ; i < result.length ; i++) {
        let mresult = await db.Model.findAll({
                                            where:{
                                                x : X,
                                                w : W,
                                                z : z
                                            })
        if(mresult[i].x == null || mresult[i].x == undefined){
             update(): // something like that
             break; // <------------- Break it like this
        }
        if(mresult[i].w > 0){
             break; // <------------- Break it like this
        }
        if(mresult[i].z < 100){
             break; // <------------- Break it like this
        }
    }    
}

【讨论】:

  • 调试nowww.. :)
  • await 是保留字
  • 检查你的节点版本?它应该是 7/8+
  • 然后检查 async/await 的语法,flow 100% 正确,应该有语法,请检查。
猜你喜欢
  • 1970-01-01
  • 2014-03-12
  • 2017-07-26
  • 2021-02-28
  • 2015-10-07
  • 2018-01-19
  • 2020-05-15
  • 1970-01-01
  • 2017-11-23
相关资源
最近更新 更多