最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass arguments to a promise? - Stack Overflow

programmeradmin2浏览0评论

In the examples I see, the code in a promise is static. An example:

var promise = new Promise(function (resolve,reject) {
  if (true)
    resolve("It is a success!")
  else
    reject(("It is a failure."));
});

promise.then(function (x) {
   alert(x);
}).catch(function (err) {
      alert("Error: " + err);
    });

How do I pass arguments to the promise so that useful work can be done? Is it by the use of global variables?

In the examples I see, the code in a promise is static. An example:

var promise = new Promise(function (resolve,reject) {
  if (true)
    resolve("It is a success!")
  else
    reject(("It is a failure."));
});

promise.then(function (x) {
   alert(x);
}).catch(function (err) {
      alert("Error: " + err);
    });

How do I pass arguments to the promise so that useful work can be done? Is it by the use of global variables?

Share Improve this question asked Mar 30, 2017 at 16:04 u936293u936293 16.3k34 gold badges121 silver badges221 bronze badges 6
  • 1 right now alert(x) would alert("It is a success!"), you can change that string to be whatever you want. – Joe Lissner Commented Mar 30, 2017 at 16:07
  • You can pass an object to the resolve callback: resolve({status: 'success', message: "It is a success!"})(For example) and in the resolve callback you can access it like alert(x.message); or alert(x.status); – Alon Eitan Commented Mar 30, 2017 at 16:09
  • 1 Not global variables, but usually you'll just use any variables in scope at the time the Promise is created. – deceze Commented Mar 30, 2017 at 16:10
  • Just as always, put the value you are creating in a function and let it depend on the parameters?! Your question is the same as "How to pass arguments to a string?" or "How to pass arguments to an object literal?". – Bergi Commented Mar 30, 2017 at 16:20
  • What do you consider to be "useful work"? – Bergi Commented Mar 30, 2017 at 16:21
 |  Show 1 more ment

1 Answer 1

Reset to default 4

Usually it may be done with the following code:

function getSomePromise(myVar) {
  var promise = new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
  return promise;
}

var variableToPass = true;
getSomePromise(variableToPass).then(function (x) {
  alert(x);
}).catch(function (err) {
  alert("Error: " + err);
});

Update:

As @AlonEitan suggested, you can simplify getSomePromise function:

function getSomePromise(myVar) {
  return new Promise(function (resolve,reject) {
    if (myVar)
      resolve("It is a success!")
    else
      reject(("It is a failure."));
  });
}
发布评论

评论列表(0)

  1. 暂无评论