我看到的代码是这样的:
myObj.doSome("task").then(function(env) {
// logic
});
那么()从何而来?
我看到的代码是这样的:
myObj.doSome("task").then(function(env) {
// logic
});
那么()从何而来?
当前回答
我猜doSome会返回这个,也就是myObj,它也有then方法。标准方法链接…
如果doSome不返回this,作为doSome执行的对象,请放心,它将返回具有then方法的某个对象…
正如@patrick指出的,标准js中没有then()
其他回答
我猜doSome会返回这个,也就是myObj,它也有then方法。标准方法链接…
如果doSome不返回this,作为doSome执行的对象,请放心,它将返回具有then方法的某个对象…
正如@patrick指出的,标准js中没有then()
".then()"函数广泛用于Windows 8 Store应用程序异步编程中的承诺对象。 据我所知,它在某种程度上像一个回调。
在本文档中查找详细信息 http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx
当然,它也可以是任何其他已定义函数的名称。
这是我为自己做的一个东西,用来弄清楚事情是如何运作的。我想其他人也会发现这个具体的例子很有用:
doit().then(function() { log('Now finally done!') }); log('---- But notice where this ends up!'); // For pedagogical reasons I originally wrote the following doit()-function so that // it was clear that it is a promise. That way wasn't really a normal way to do // it though, and therefore Slikts edited my answer. I therefore now want to remind // you here that the return value of the following function is a promise, because // it is an async function (every async function returns a promise). async function doit() { log('Calling someTimeConsumingThing'); await someTimeConsumingThing(); log('Ready with someTimeConsumingThing'); } function someTimeConsumingThing() { return new Promise(function(resolve,reject) { setTimeout(resolve, 2000); }) } function log(txt) { document.getElementById('msg').innerHTML += txt + '<br>' } <div id='msg'></div>
then()函数与一些库或框架(如jQuery或AngularJS)中使用的“Javascript承诺”相关。
promise是一种处理异步操作的模式。该承诺允许您调用一个名为“then”的方法,该方法允许您指定作为回调函数使用的函数。
欲了解更多信息,请参阅:http://wildermuth.com/2013/8/3/JavaScript_Promises
对于Angular的承诺:http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/
.然后在async函数中返回一个promise。
好的例子是:
var doSome = new Promise(function(resolve, reject){
resolve('I am doing something');
});
doSome.then(function(value){
console.log(value);
});
要向它添加另一个逻辑,您还可以添加reject('I am the rejected param')调用函数和console.log。