我有一个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) async
在await
循环中使用是否有任何问题?我正在尝试循环遍历文件数组和forEach
每个文件的内容.
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
Run Code Online (Sandbox Code Playgroud)
这段代码确实有效,但这可能会出错吗?我有人告诉我你不应该使用await
这样的高阶函数,所以我只是想问一下这是否有任何问题.
我看到有一个eslint规则,no-return-await
禁止return await
.
在规则的描述中,它表示return await
添加"extra time before the overarching Promise resolves or rejects"
.
但是,当我查看MDN async
函数文档时,"简单示例"显示了一个示例,其中return await
不包含任何可能导致性能问题的描述.
是return await
一个实际的性能问题,因为eslint文档建议?
如果是这样,怎么样?
await 的可能重复 仅在 async 函数中有效。
我是新手NodeJS
,我发现这个概念async-await
有点混乱。经过一些阅读和混乱之后,这就是我的理解。
假设,我有一个sum
这样的功能。
function sum(a, b) {
// print the numbers
for (var i = 0; i < 100000; i++) {
console.log(i);
}
// settimeout
new Promise (resolve => {
setTimeout(resolve, 1000);
});
return a+b;
}
function main() {
let a = sum(5,2);
console.log(a);
}
main();
Run Code Online (Sandbox Code Playgroud)
它为计时器分配一个新线程并继续正常流程。它首先打印所有数字,返回a 7
,然后在退出前等待1 秒。
但是现在我想按照它们的写入顺序执行这些行。await
在 timer 之前放置一个关键字是有意义的Promise
。
async function sum(a, b) {
// print the numbers
for (var …
Run Code Online (Sandbox Code Playgroud) 我需要让代码休眠,直到满足某些条件或超过 3 秒超时。然后返回一个简单的字符串。无论如何我可以做到这一点吗?
// this function needs to return a simple string
function something() {
var conditionOk = false;
var jobWillBeDoneInNMiliseconds = Math.floor(Math.random() * 10000);
setTimeout(function() {
// I need to do something here, but I don't know how long it takes
conditionOk = true;
}, jobWillBeDoneInNMiliseconds);
// I need to stop right here until
// stop here until ( 3000 timeout is passed ) or ( conditionOk == true )
StopHereUntil( conditionOk, 3000 );
return "returned something";
}
Run Code Online (Sandbox Code Playgroud)
这就是我要做的: …
在给定的示例中,演示了如何从自定义模块导出变量或函数。如何以类似的方式导出异步函数,然后从 app.js 调用它,如下所示:
// app.js
var things = require("./someThings");
await things.getSomeThingsAsync();
Run Code Online (Sandbox Code Playgroud)
编辑:
上述链接指向的示例(Stackoverflow 上的答案)包含以下代码:
// someThings.js
(function() {
var someThings = ...;
...
module.exports.getSomeThings = function() {
return someThings();
}
}());
// main.js
var things = require("someThings");
...
doSomething(things.getSomeThings());
Run Code Online (Sandbox Code Playgroud)
假设模块的封装函数内部存在一个异步函数,您希望将其公开给导入该模块的任何人。例如:
(function() {
...
const doSomethingAsync = (time) => {
return new Promise(resolve => {
setTimeout(() => resolve(42), time)
})
}
//const doSomething = async () => {
async function doSomething () {
let answer1 = await doSomethingAsync(3000)
let …
Run Code Online (Sandbox Code Playgroud) 我已经编写了一个代码来使用 promise 从异步调用中返回一些数据。当我尝试执行时,我得到“语法错误等待仅在异步函数中有效”,并且我得到无法代理应用程序请求...错误:连接 ECONNREFUSED。
我不确定为什么会出现这些错误
我曾尝试在函数调用之前使用 async,但没有奏效
var http = require('https');
var httpGet = function(url) {
return new Promise (function(resolve, reject) {
http.get(url,function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk){
body += chunk;
console.log("The body is "+ body);
});
res.on('end',function(){resolve(body);});
}).on('error', reject);
});
};
var body = await httpGet('link');
$.response.setBody(body);
Run Code Online (Sandbox Code Playgroud)
我希望变量体具有从 httpGet 函数返回的数据。现在我收到了上述错误。但是不使用 await,我将 body 的值设为“{}”。
请帮忙
我试图异步运行一个函数 20 次。我有函数定义:
import axios from 'axios';
async function updateUser (url, user) {
return new Promise((resolve, reject) => {
axios.put(url, JSON.stringify(user))
.then(response => {
//Folio returned code 204
console.log('The user has been updated');
resolve(response.data);
}).catch((err) => {
//Folio returned error
console.error(`Error Text: ${err.response.data}`);
console.error(`Error Code: ${err}`);
});
});
};
export {updateUser};
Run Code Online (Sandbox Code Playgroud)
然后我尝试在外部 JSON 中循环用户,并将它们一次更新到我的系统 20:
import {updateUser} from './updateUser.js';
import usersjson from './jsons/users.json';
let promises=[];
if (usersjson.users.length) {
try {
for (const user of usersjson.users) {
update = new promise …
Run Code Online (Sandbox Code Playgroud) javascript ×6
asynchronous ×5
node.js ×5
async-await ×4
ajax ×1
arrays ×1
for-loop ×1
jquery ×1
node-modules ×1
promise ×1
sleep ×1