我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我想在我的前端应用程序中使用(本机)promises来执行XHR请求,但没有庞大框架的所有tomfoolery.
我希望我的XHR返回的希望,但是,这并不工作(给我:Uncaught TypeError: Promise resolver undefined is not a function)
function makeXHRRequest (method, url, done) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() { return new Promise().resolve(); };
xhr.onerror = function() { return new Promise().reject(); };
xhr.send();
}
makeXHRRequest('GET', 'http://example.com')
.then(function (datums) {
console.log(datums);
});
Run Code Online (Sandbox Code Playgroud) 我有一个简单的节点模块,它连接到一个数据库,并有几个接收数据的函数,例如这个函数:
dbConnection.js:
import mysql from 'mysql';
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'db'
});
export default {
getUsers(callback) {
connection.connect(() => {
connection.query('SELECT * FROM Users', (err, result) => {
if (!err){
callback(result);
}
});
});
}
};
Run Code Online (Sandbox Code Playgroud)
该模块将从不同的节点模块以这种方式调用:
app.js:
import dbCon from './dbConnection.js';
dbCon.getUsers(console.log);
Run Code Online (Sandbox Code Playgroud)
我想使用promises而不是回调来返回数据.到目前为止,我已经阅读了以下线程中的嵌套promise:使用嵌套Promise编写清洁代码,但我找不到任何对这个用例来说足够简单的解决方案.result使用承诺返回的正确方法是什么?
这不是一个现实世界的问题,我只是想了解如何创造承诺.
我需要了解如何为一个不返回任何内容的函数做出承诺,比如setTimeout.
假设我有:
function async(callback){
setTimeout(function(){
callback();
}, 5000);
}
async(function(){
console.log('async called back');
});
Run Code Online (Sandbox Code Playgroud)
如何创建一个async可以在setTimeout准备好后返回的承诺callback()?
我想包装它会带我到某个地方:
function setTimeoutReturnPromise(){
function promise(){}
promise.prototype.then = function() {
console.log('timed out');
};
setTimeout(function(){
return ???
},2000);
return promise;
}
Run Code Online (Sandbox Code Playgroud)
但我想不到这一点.
我有以下功能,试图使用Promises.
var getDefinitions = function() {
return new Promise(function(resolve) {
resolve(ContactManager.request("definition:entities"));
});
}
var definitions = getDefinitions()
Run Code Online (Sandbox Code Playgroud)
definitions 正在回归:
Promise {
[[PromiseStatus]]: "resolved",
[[PromiseValue]]: child
}
Run Code Online (Sandbox Code Playgroud)
我想获得PromiseValue的价值,但要求
var value = definitions.PromiseValue; // undefined
Run Code Online (Sandbox Code Playgroud)
给了我一个不确定的结果.
我的问题是双括号是什么PromiseValue意思,我该如何检索它的值[[ ]].
当我开始研究Promises时,我的理解已经停止在我未发现的下面的问题上(我发现所有这些都是对Promise构造函数的具体讨论,以及Promise' then'函数 - 但不是一个比较它们的设计模式的讨论).
1. Promise构造函数
从MDN文档中,我们使用了Promise构造函数(添加了我的注释):
new Promise(function(resolve, reject) { ... }); // <-- Call this Stage 1
Run Code Online (Sandbox Code Playgroud)
带有两个参数的函数对象
resolve和reject.第一个参数履行承诺,第二个参数拒绝承诺.一旦我们的操作完成,我们可以调用这些函数.
2. then功能
移动到then功能,可以在一个被称为Promise对象(返回一个新的Promise对象),我们有由文档中描述的以下函数签名(加上我的意见):
p.then(onFulfilled, onRejected);
Run Code Online (Sandbox Code Playgroud)
链接
因为该
then方法返回Promise,所以您可以轻松地链接然后调用.
var p2 = new Promise(function(resolve, reject) {
resolve(1); // <-- Stage 1 again
});
p2.then(function(value) {
console.log(value); // 1
return value + 1; // <-- Call …Run Code Online (Sandbox Code Playgroud) 这可能是一个noob问题,但我是承诺的新手,并试图找出如何在node.js中使用Q.
我看到教程以a开头
promiseMeSomething()
.then(function (value) {}, function (reason) {});
Run Code Online (Sandbox Code Playgroud)
但是我没有意识到它究竟.then来自哪里.我想它来自
var outputPromise = getInputPromise()
.then(function (input) {}, function (reason) {});
Run Code Online (Sandbox Code Playgroud)
但是哪里getInputPromise()来的?我发现以前没有提到它.
我已将它包含在我的项目中
var Q = require('q');
// this is suppose, the async function I want to use promise for
function async(cb) {
setTimeout(function () {
cb();
}, 5000);
}
async(function () {
console.log('async called back');
});
Run Code Online (Sandbox Code Playgroud)
我如何在我的例子中使用Q它.then?
我一直在为我自己使用的小型2D游戏库工作,我遇到了一些问题.库中有一个名为loadGame的特定函数,它将依赖信息作为输入(资源文件和要执行的脚本列表).这是一个例子.
loadGame({
"root" : "/source/folder/for/game/",
"resources" : {
"soundEffect" : "audio/sound.mp3",
"someImage" : "images/something.png",
"someJSON" : "json/map.json"
},
"scripts" : [
"js/helperScript.js",
"js/mainScript.js"
]
})
Run Code Online (Sandbox Code Playgroud)
资源中的每个项目都有一个密钥,游戏使用该密钥来访问该特定资源.loadGame函数将资源转换为promises对象.
问题是它试图使用Promises.all来检查它们何时准备就绪,但是Promise.all只接受迭代作为输入 - 所以像我所拥有的对象是不可能的.
所以我尝试将对象转换为数组,这很有效,除了每个资源只是数组中的一个元素,并且没有用于标识它们的键.
这是loadGame的代码:
var loadGame = function (game) {
return new Promise(function (fulfill, reject) {
// the root folder for the game
var root = game.root || '';
// these are the types of files that can be loaded
// getImage, getAudio, and getJSON are defined elsewhere in my code - they …Run Code Online (Sandbox Code Playgroud) javascript ×10
promise ×9
q ×4
bluebird ×3
es6-promise ×3
asynchronous ×2
node.js ×2
ajax ×1
callback ×1
ecmascript-6 ×1
jquery ×1
settimeout ×1