【问题标题】:Example of promise without asynchronous code?没有异步代码的承诺示例?
【发布时间】:2020-02-28 22:14:39
【问题描述】:

我正在尝试了解承诺的机制。具体来说,我们可以将什么都传递给第一个参数(通常称为解析)。例如:

function getFoo(url){
    return new Promise(function(resolve, reject) {
        let httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', url);
        httpRequest.onload = function(){
            if(httpRequest ===200) {resolve(httpRequest.responseText);
            } else{ reject(Error(httpRequest.status));}
        }
        httpRequest.send();
    });
}

我正在尝试构建自己的函数,该函数可以从 Promise 中受益(所有示例都使用 setTimeout 或 ajax 代码)。任何人都可以提供一个使用 promise 的常规函数​​的简单示例(即使在这种情况下不需要该机制),以便我可以构建自己的函数,将某些东西传递给 resolve 回调?谢谢

例如:

function getFoo(param){
    return new Promise(function(resolve, reject) {
        ????myFoo () { ...return...}
         resolve(myFoo);

            } else{ reject(???);}
        }
    });
}

【问题讨论】:

  • what all can we pass to the first parameter (usually called resolve) 几乎任何东西。 Promise 是一个代表最终值的对象。 resolve 是您定义该值的方式。
  • All the exapmples use either setTimeout or ajax code ... 你见过任何使用SubtleCrypto 的代码吗?这都是基于promise 的——你为什么要对同步代码使用promise——这很奇怪

标签: javascript promise callback


【解决方案1】:

我们可以将什么都传递给第一个参数(通常称为解析)

resolve 只接受一个参数,但你可以向参数传递任何东西,它可以是数组、对象、函数……基本上是 javascript 支持的任何数据类型。

下面是一个简单的 Promise 示例。

PS 注意:promise 对象只有在调用 then 函数时才会被调用,并且是 then 函数接受回调进行 resolve 并拒绝。

function callPromise() {

  return new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (true) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

}

callPromise().then(function(success){
   console.log(success);
}, function(error)
{
  console.log(error);
})

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多