2017-04-14 47 views
-2

我觉得我在这里忽略了一些东西,但我试图编写一个返回同步值的函数,但是在内部它需要一些可以只能被提取异步:如何在需要同步返回的函数中使用异步值

// Gets something asynchronously 
const getValueAsync = Promise.resolve('value') 

// Needs to return a value synchronously 
const returnSyncValue =() => { 
    // Needs the async data here 
    getValueAsync 

    // Modify it 


    // Return the result sync 
} 

// So that this will work: 
const value = returnSyncValue() 

我正在使用最新版本的节点。有没有办法在不改变returnSyncValue的实现的情况下实现这一点(即使它同步)?

+1

这是不可能的异步同步 - 你只需要考虑一秒钟,以实现为什么 –

+1

http://stackoverflow.com/questions/14220321/how-do-i-return-the-response异步调用 – dm03514

+1

异步性是病毒性的:一旦你使用了一个异步函数,其他的一切都必须是异步的。 – robertklep

回答

0

简短的回答:没有

龙答:

,因为当你做const value = returnSyncValue(),你还没有得到异步值然而,你不能做到这一点。因此没有价值分配。

0

使用await

// Gets something asynchronously 
const getValueAsync = Promise.resolve('value') 

// Needs to return a value synchronously 
const returnSyncValue =() => { 
    // Needs the async data here 
    var result = await getValueAsync() 

    // Modify it 
    result = "newData" 

    // Return the result sync 
    return result 
} 

// So that this will work: 
const value = returnSyncValue() 

注意:您需要node.js 7及更高版本。

0

简答题,没有。

很长的答案,大多数接口接受承诺作为返回值。在JavaScript中,你不能阻止它,因为它挂断了其他所有事情。一个正确实施的库可能会有回调或接受价值作为承诺和链接。

如果是您自己的实施,请考虑改进以链接Promise。