【问题标题】:How can I pass the variable in es6 promise then callback to the outside如何在 es6 Promise 中传递变量然后回调到外部
【发布时间】:2017-06-21 13:14:04
【问题描述】:

代码在这里:

function square() {
  let record = 10;
  new Promise(function(resolve, reject) {
    // A mock async action using setTimeout
    setTimeout(function() { resolve(record); }, 3000);
  })
    .then(function(data) { 
      console.log('first then: ', data);
      return data * data;
    });
  return record;
 }

function submit() {
  // ...
  const result = square(); // => still 10
  // finalHandler(result);
}
submit();

我使用 setTimeout 来模拟我必须交付的一个异步进程。当我调用提交时,result 传递给finalHandler 仍然是初始值 10。但是我更新的结果是什么,即 100。如何修改 squaresubmit 函数?

【问题讨论】:

标签: javascript asynchronous ecmascript-6 promise


【解决方案1】:

您需要通过返回承诺使square 异步:

function square() {
  let record = 10;
  return new Promise(function(resolve, reject) {
    // A mock async action using setTimeout
    setTimeout(function() { resolve(record); }, 3000);
  })
    .then(function(data) { 
      console.log('first then: ', data);
      return data * data;
    });
 }

function submit() {
  // ...
  square()
     .then(result => finalHandler(result);
}
submit();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 2017-08-11
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多