- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
这个问题在这里已经有了答案:
How to return the response from an asynchronous call
(42 个回答)
3年前关闭。
我有一个 es6 类,带有 init()
方法负责获取数据,转换数据,然后更新类的属性 this.data
使用新转换的数据。
到现在为止还挺好。
类本身还有另一个 getPostById()
方法,只是做它听起来像的事情。这是该类的代码:
class Posts {
constructor(url) {
this.ready = false
this.data = {}
this.url = url
}
async init() {
try {
let res = await fetch( this.url )
if (res.ok) {
let data = await res.json()
// Do bunch of transformation stuff here
this.data = data
this.ready = true
return data
}
}
catch (e) {
console.log(e)
}
}
getPostById(id){
return this.data.find( p => p.id === id )
}
}
async/await
init()
中的机制方法。
let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')
allPosts.init()
.then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console
allPosts.getPostById(4)
作为
return
一个函数?
let myFunc = async () => {
const postId = 4
await allPosts.init() // I need to wait for this to finish before returning
// This is logging correct value
console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )
// How can I return the RESULT of allPosts.getPostById( postId ) ???
return allPosts.getPostById( postId )
}
myFunc()
返回
Promise
但不是最终值。我已经阅读了几篇关于这个主题的相关文章,但它们都给出了日志记录的例子,再也没有回来。
init()
:使用
Promise
并使用
async/await
.无论我尝试什么,我都无法使用
getPostById(id)
的最终值.
getPostById(id)
的值?
init()
正确返回。然而,在主事件循环中:它返回
一个 promise ,那么我的工作就是从
中获取这个 Promise 的结果。有点 并行循环(不是新的真正线程)。为了从并行循环中捕获结果,有两种方法:
.then( value => doSomethingWithMy(value) )
let value = await myAsyncFn()
.现在这是愚蠢的打嗝:await can only be used within an
async
function :p
await
应该嵌入到
async
中函数,可用于
await
等等...
.then()
或
async/await
.
最佳答案
至于你的评论;我将其添加为答案。
您用 JavaScript 编写的代码在一个线程上运行,这意味着如果您的代码实际上可以等待某些东西,它将阻止您执行任何其他代码。 JavaScript 的事件循环在 this video 中有很好的解释如果您喜欢阅读 this page .
在浏览器中阻止代码的一个很好的例子是 alert("cannot do anything until you click ok");
.警报会阻止所有内容,用户甚至无法滚动或单击页面中的任何内容,您的代码也会阻止执行。
Promise.resolve(22)
.then(x=>alert("blocking")||"Hello World")
.then(
x=>console.log(
"does not resolve untill you click ok on the alert:",
x
)
);
fetch
但是 fetch 需要一些时间才能完成,并且您的函数不应阻塞(必须尽快返回某些内容)。这就是 fetch 返回一个 promise 的原因。
then
的对象。函数(还有一堆东西是糖,但做同样的事情),这个函数需要 2 个参数。
traditionalApi(
arg
,function callback(err,value){
err ? handleFail(err) : processValue(value);
}
);
new Promise
将传统的 api 转换为 promises
const apiAsPromise = arg =>
new Promise(
(resolve,reject)=>
traditionalApi(
arg,
(err,val) => (err) ? reject(err) : resolve(val)
)
)
const handleSearch = search =>
compose([
showLoading,
makeSearchRequest,
processRespose,
hideLoading
])(search)
.then(
undefined,//don't care about the resolve
compose([
showError,
hideLoading
])
);
async await
实际上并没有启动另一个线程,
async
函数总是返回一个 promise 和
await
实际上并不阻塞或等待。这是
someFn().then(result=>...,error=>...)
的语法糖看起来像:
async someMethod = () =>
//syntax sugar for:
//return someFn().then(result=>...,error=>...)
try{
const result = await someFn();
...
}catch(error){
...
}
}
try catch
但你不需要这样做,例如:
var alwaysReject = async () => { throw "Always returns rejected promise"; };
alwaysReject()
.then(
x=>console.log("never happens, doesn't resolve")
,err=>console.warn("got rejected:",err)
);
await
返回一个被拒绝的 promise 将导致异步函数返回一个被拒绝的 promise (除非你试图捕获它)。很多时候希望让它失败并让调用者处理错误。
Promise.all
,这需要一个 promise 数组并返回一个新的 promise ,该 promise 解析为一个已解析值的数组
或当其中任何一个拒绝时拒绝 .您可能只想获取所有 promise 的结果并过滤掉被拒绝的结果:
const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
urls.map(//map array of urls to array of promises that don't reject
url =>
fetch(url)
.then(
undefined,//do not handle resolve yet
//when you handle the reject this ".then" will return
// a promise that RESOLVES to the value returned below (new Fail([url,err]))
err=>new Fail([url,err])
)
)
)
.then(
responses => {
console.log("failed requests:");
console.log(
responses.filter(//only Fail type
isFail
)
);
console.log("resolved requests:");
console.log(
responses.filter(//anything not Fail type
response=>!isFail(response)
)
);
}
);
关于javascript - 异步函数不返回值,但 console.log() 执行 : how to do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47664598/
C语言sscanf()函数:从字符串中读取指定格式的数据 头文件: ?
最近,我有一个关于工作预评估的问题,即使查询了每个功能的工作原理,我也不知道如何解决。这是一个伪代码。 下面是一个名为foo()的函数,该函数将被传递一个值并返回一个值。如果将以下值传递给foo函数,
CStr 函数 返回表达式,该表达式已被转换为 String 子类型的 Variant。 CStr(expression) expression 参数是任意有效的表达式。 说明 通常,可以
CSng 函数 返回表达式,该表达式已被转换为 Single 子类型的 Variant。 CSng(expression) expression 参数是任意有效的表达式。 说明 通常,可
CreateObject 函数 创建并返回对 Automation 对象的引用。 CreateObject(servername.typename [, location]) 参数 serv
Cos 函数 返回某个角的余弦值。 Cos(number) number 参数可以是任何将某个角表示为弧度的有效数值表达式。 说明 Cos 函数取某个角并返回直角三角形两边的比值。此比值是
CLng 函数 返回表达式,此表达式已被转换为 Long 子类型的 Variant。 CLng(expression) expression 参数是任意有效的表达式。 说明 通常,您可以使
CInt 函数 返回表达式,此表达式已被转换为 Integer 子类型的 Variant。 CInt(expression) expression 参数是任意有效的表达式。 说明 通常,可
Chr 函数 返回与指定的 ANSI 字符代码相对应的字符。 Chr(charcode) charcode 参数是可以标识字符的数字。 说明 从 0 到 31 的数字表示标准的不可打印的
CDbl 函数 返回表达式,此表达式已被转换为 Double 子类型的 Variant。 CDbl(expression) expression 参数是任意有效的表达式。 说明 通常,您可
CDate 函数 返回表达式,此表达式已被转换为 Date 子类型的 Variant。 CDate(date) date 参数是任意有效的日期表达式。 说明 IsDate 函数用于判断 d
CCur 函数 返回表达式,此表达式已被转换为 Currency 子类型的 Variant。 CCur(expression) expression 参数是任意有效的表达式。 说明 通常,
CByte 函数 返回表达式,此表达式已被转换为 Byte 子类型的 Variant。 CByte(expression) expression 参数是任意有效的表达式。 说明 通常,可以
CBool 函数 返回表达式,此表达式已转换为 Boolean 子类型的 Variant。 CBool(expression) expression 是任意有效的表达式。 说明 如果 ex
Atn 函数 返回数值的反正切值。 Atn(number) number 参数可以是任意有效的数值表达式。 说明 Atn 函数计算直角三角形两个边的比值 (number) 并返回对应角的弧
Asc 函数 返回与字符串的第一个字母对应的 ANSI 字符代码。 Asc(string) string 参数是任意有效的字符串表达式。如果 string 参数未包含字符,则将发生运行时错误。
Array 函数 返回包含数组的 Variant。 Array(arglist) arglist 参数是赋给包含在 Variant 中的数组元素的值的列表(用逗号分隔)。如果没有指定此参数,则
Abs 函数 返回数字的绝对值。 Abs(number) number 参数可以是任意有效的数值表达式。如果 number 包含 Null,则返回 Null;如果是未初始化变量,则返回 0。
FormatPercent 函数 返回表达式,此表达式已被格式化为尾随有 % 符号的百分比(乘以 100 )。 FormatPercent(expression[,NumDigitsAfterD
FormatNumber 函数 返回表达式,此表达式已被格式化为数值。 FormatNumber( expression [,NumDigitsAfterDecimal [,Inc
我是一名优秀的程序员,十分优秀!