Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从函数值中打破承诺映射?_Javascript_Promise_Bluebird - Fatal编程技术网

Javascript 从函数值中打破承诺映射?

Javascript 从函数值中打破承诺映射?,javascript,promise,bluebird,Javascript,Promise,Bluebird,在下面的示例代码中,您可以看到我有一个正在映射的函数链,当抛出错误时,该链将退出。全局x的值从第一个函数设置为bar,但从第三个函数设置为baz,因为它从不运行 var x = "foo" Promise.map([ function(){ x = "bar" return true }, function(){ throw new Error() }, function(){ x = "baz" return true } ],

在下面的示例代码中,您可以看到我有一个正在映射的函数链,当抛出错误时,该链将退出。全局
x
的值从第一个函数设置为
bar
,但从第三个函数设置为
baz
,因为它从不运行

var x = "foo"

Promise.map([
  function(){
    x = "bar"
    return true
  },
  function(){
    throw new Error()
  },
  function(){
    x = "baz"
    return true
  }
], function(fn){
  return Promise.method(fn)()
})
.catch(function(e){
  console.log(e) // [Error]
})
.then(function(){
  console.log(x) // "bar"
})
但是,当我在map函数中打开promise并插入一个有条件抛出的错误
x
时,它将更改为
baz
,第三个函数将运行

var x = "foo"

Promise.map([
  function(){
    x = "bar"
    return true
  },
  function(){
    return "bad value throw error"
  },
  function(){
    x = "baz"
    return true
  }
], function(fn){
  return Promise.method(fn)().then(function(val){
    if(val == "bad value throw error") throw new Error()
    return val
  })
})
.catch(function(e){
  console.log(e) // [Error]
})
.then(function(){
  console.log(x) // "baz"
})
如何在承诺映射中插入一个错误并抛出该错误以破坏映射链


是否还有另一种bluebird方法可以运行一系列承诺?

这里的答案是使用
每个
而不是
映射

var x = "foo"

Promise.each([
  function(){
    x = "bar"
    return true
  },
  function(){
    return "bad value throw error"
  },
  function(){
    x = "baz"
    return true
  }
], function(fn){
  return Promise.method(fn)().then(function(val){
    if(val == "bad value throw error") throw new Error()
    return val
  })
})
.catch(function(e){
  console.log(e) // [Error]
})
.then(function(){
  console.log(x) // "baz"
})

如果你想并行运行这些函数,为什么你希望它们在抛出错误之前就停止运行?这是一个输入错误,我想让它们串联运行。是的,然后使用
{concurrency:1}
选项。@Bergi我试过了,这里有一个问题,你能解释为什么使用
每个
而不是
映射吗?