为什么在foreach函数回调中对全局变量所做的更改未反映出该回调

时间:2019-02-01 15:29:17

标签: javascript mongodb asynchronous foreach

我正在尝试从mongoDB地图集检索一些文档,下面是代码:

exec spx_SELECT_LocalizacoesEtiquetas 


GO
IF OBJECT_ID('dbo.spx_SELECT_LocalizacoesEtiquetas') IS NOT NULL
DROP PROCEDURE spx_SELECT_LocalizacoesEtiquetas
GO
CREATE PROCEDURE spx_SELECT_LocalizacoesEtiquetas   

AS
BEGIN
SET NOCOUNT ON 

DECLARE @SQL NVARCHAR(MAX); 
    SET @SQL = 

'SELECT ET0109 AS Localizacao, Etiquetas
FROM OpenQuery(MACPAC, ''SELECT FET001.ET0109,  FET001.ET0101 AS Etiquetas
FROM AUTO.D805DATPOR.FET001 FET001
WHERE FET001.ET0104=''''POE'''' AND FET001.ET0105=''''DIS'''''' AND FET001.ET0101 = ''''' 
+ (SELECT Localizacao FROM xLocalizacao WHERE InventarioID = 1 ) +  ''''' ) ';

EXEC sp_executesql @SQL

END

第一个console.log输出更新的pageBuckets数组,但是第二个console.log输出一个空数组。我无法理解问题所在。

1 个答案:

答案 0 :(得分:0)

结果是第二个console.log在foreach循环之前被执行,因此请使用以下代码对其进行修复:

result.forEach(el =>{
        pageBuckets.push(el);
          console.log(pageBuckets) //1
      }).then(() =>{
        console.log(pageBuckets); //2
      })