我有一个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) 我知道有很多这样的话题.我知道基础知识:.forEach()在原始数组和.map()新数组上运行.
就我而言:
function practice (i){
return i+1;
};
var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);
Run Code Online (Sandbox Code Playgroud)
这是输出:
[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ] …Run Code Online (Sandbox Code Playgroud) 我最近一直在搞乱fetch()api,并注意到一些有点古怪的东西.
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => {
return {
data: response.json(),
status: response.status
}
})
.then(post => document.write(post.data));
;
Run Code Online (Sandbox Code Playgroud)
post.data返回一个promise对象. http://jsbin.com/wofulo/2/edit?js,output
但是如果写成:
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => response.json())
.then(post => document.write(post.title));
;
Run Code Online (Sandbox Code Playgroud)
post这里是一个标准对象,您可以访问title属性. http://jsbin.com/wofulo/edit?js,output
所以我的问题是:为什么response.json在对象文字中返回一个promise,但是如果刚刚返回则返回值?
在我的NodeJS代码中,我需要进行2或3次API调用,每次调用都会返回一些数据.完成所有API调用后,我想将所有数据收集到一个JSON对象中以发送到前端.
我知道如何使用API回调(下一次调用将在前一次调用的回调中发生),但这会很慢:
//1st request
request('http://www.example.com', function (err1, res1, body) {
//2nd request
request('http://www.example2.com', function (err2, res2, body2) {
//combine data and do something with it
});
});
Run Code Online (Sandbox Code Playgroud)
我知道你也可以做类似的事情并且更符合承诺,但我认为同样的概念适用于下一个调用在当前调用完成之前不会执行的情况.
有没有办法同时调用所有函数,但是我的最后一段代码是等待所有API调用完成并在执行之前提供数据?
我从多个网址抓取内容.Fetch api全面使用promises.
所以我的一个请求的代码看起来像这样
fetch(url).then((response)=>response.text()).then(function(html) { //stuff });
现在我有一系列的网址和多个电话将如何知道所有电话是否已经完成.
我尝试使用,Promise.all但如果你看到每个请求有两个承诺.有没有更好的方法,也是Promise.all支持也不是那么好.
如何使用 Promise.all 获取 api json 数据?如果我不使用 Promise.all,它可以很好地拉动它。使用 .all 它实际上在控制台中返回查询的值,但由于某种原因我无法访问它。这是我的代码以及它在解决后在控制台中的外观。
Promise.all([
fetch('data.cfc?method=qry1', {
method: 'post',
credentials: "same-origin",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: $.param(myparams0)
}),
fetch('data.cfc?method=qry2', {
method: 'post',
credentials: "same-origin",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: $.param(myparams0)
})
]).then(([aa, bb]) => {
$body.removeClass('loading');
console.log(aa);
return [aa.json(),bb.json()]
})
.then(function(responseText){
console.log(responseText[0]);
}).catch((err) => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
我想要的只是能够访问 data.qry1。我尝试使用 responseText[0].data.qry1 或 responseText[0]['data']['qry1'] 但它返回未定义。下面是 console.log responseText[0] 的输出。console.log(aa) 给出 Response {type: "basic" ...
Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
data: {qry1: Array(35)} …Run Code Online (Sandbox Code Playgroud) 我的目标是从两个 URL 获取数据,并仅在两个 URL 均成功返回时才执行操作。另一方面,如果其中任何一个失败,我想返回错误。我已经尝试了我的代码并设法获得了预期的效果。
我的问题是,是否有更有效、更简洁的方法来实现相同的功能?
辅助函数
let status = (r) => {
if (r.ok) {
return Promise.resolve(r)
} else {
return Promise.reject(new Error(r.statusText))
}
}
let json = (r) => r.json();
Run Code Online (Sandbox Code Playgroud)
要求
let urls = [
'http://localhost:3000/incomplete',
'http://localhost:3000/complete'
]
let promises = urls.map(url => {
return fetch(url)
.then(status)
.then(json)
.then(d => Promise.resolve(d))
.catch(e => Promise.reject(new Error(e)));
});
Promise.all(promises).then(d => {
// do stuff with d
}).catch(e => {
console.log('Whoops something went wrong!', e);
});
Run Code Online (Sandbox Code Playgroud) 我有一个包含 4 个请求对象的数组,我想在这些对象上使用 Fetch API 并取回承诺。然后我想解决这些承诺中的每一个并取回价值。
这是我构建请求对象的方式。
let requestsArray = urlArray.map((url) => {
let request = new Request(url, {
headers: new Headers({
'Content-Type': 'text/json'
}),
method: 'GET'
});
return request;
});
Run Code Online (Sandbox Code Playgroud)
这是我尝试使用的方式 Promise.all()
Promise.all(requestsArray.map((request) => {
return fetch(request).then((response) => {
return response.json();
}).then((data) => {
return data;
});
})).then((values) => {
console.log(values);
});
Run Code Online (Sandbox Code Playgroud)
最后一个console.log(values)不会向控制台打印任何内容。我用Promise.all()错了吗?
我知道第一个请求通过了,当我单独运行每个请求时,它工作正常。唯一的问题是当我尝试同时运行它们时。
javascript ×8
promise ×4
asynchronous ×3
ajax ×2
ecmascript-6 ×2
fetch-api ×2
api ×1
arrays ×1
es6-promise ×1
fetch ×1
foreach ×1
html5 ×1
jquery ×1
loops ×1
node.js ×1